﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace weba.Sales
{
    public partial class MaterialList : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!this.IsPostBack)
            {
               // UART.BLL.Sales.Material bll = new UART.BLL.Sales.Material();
                //设置经办人
           Accounts_Users currentUser = mk.l.Accounts_Users.FirstOrDefault();
                //设置根部门ID
                var bllDept = mk.l.Accounts_Department.ToList();
                this.lblRootDepartmentID.Text = bllDept.Where(j => j.ClassID == (int.Parse(currentUser.DepartmentID))).FirstOrDefault().RootID.ToString();
                this.lblStrWhere.Text = " RootDepartmentID=" + this.lblRootDepartmentID.Text;
               // this.AspNetPager.RecordCount = bll.GetCount(this.lblStrWhere.Text);
                this.BindMaterialCategoryID();
                this.BindManufacturerID();
                this.BindData();
                //设置分页页数
                this.txtPageSize.Attributes.Add("onkeydown", "javascript:SetFocusPageSize();");

            }
        }

        /// <summary>
        /// Binds the material category ID.绑定材料类型列表
        /// </summary>
        private void BindMaterialCategoryID()
        {
           // UART.BLL.Sales.MaterialCategory bll = new UART.BLL.Sales.MaterialCategory();
            var ds = mk.l.Sales_MaterialCategory.ToList();
            this.ddlMaterialCategoryID.DataSource = ds;
            this.ddlMaterialCategoryID.DataTextField = "Name";
            this.ddlMaterialCategoryID.DataValueField = "MaterialCategoryID";
            this.ddlMaterialCategoryID.DataBind();
            ListItem li = new ListItem("不限", "0");
            this.ddlMaterialCategoryID.Items.Add(li);
            this.ddlMaterialCategoryID.Items.FindByValue("0").Selected = true;
        }


        /// <summary>
        /// Binds the manufacturer ID.绑定厂家列表
        /// </summary>
        private void BindManufacturerID()
        {
           // UART.BLL.Sales.Manufacturer bll = new UART.BLL.Sales.Manufacturer();
           var ds = mk.l.Sales_Manufacturer.Where(y=>y.RootDepartmentID.ToString()==this.lblRootDepartmentID.Text).ToList();
            this.ddlManufacturerID.DataSource = ds;
            this.ddlManufacturerID.DataTextField = "ManufacturerName";
            this.ddlManufacturerID.DataValueField = "ManufacturerID";
            this.ddlManufacturerID.DataBind();
            ListItem li = new ListItem("不限", "0");
            this.ddlManufacturerID.Items.Add(li);
            this.ddlManufacturerID.Items.FindByValue("0").Selected = true;
        }

        /// <summary>
        /// 绑定订单列表
        /// </summary>
        private void BindData()
        {
           /// UART.BLL.Sales.Material bll = new UART.BLL.Sales.Material();
         var ds = mk.l.Sales_Material.ToList();
            this.myGridView.DataSource = ds;
            this.myGridView.DataBind();
        }

        /// <summary>
        /// 分页绑定数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void AspNetPager_PageChanged(object sender, EventArgs e)
        {
            this.BindData();
        }

        /// <summary>
        /// Handles the Click event of the btnSetPageSize control.设置分页页数
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSetPageSize_Click(object sender, EventArgs e)
        {
            if (this.txtPageSize.Text.Trim() != "")
            {
                if (this.txtPageSize.Text.Trim() != "0")
                {
                 //   this.AspNetPager.PageSize = int.Parse(this.txtPageSize.Text.Trim());
                    this.BindData();
                }
                else
                {
                  //  this.AspNetPager.PageSize = 10;
                    this.BindData();
                }
            }
            else
            {
               // this.AspNetPager.PageSize = 10;
                this.BindData();
            }
        }

        /// <summary>
        /// 绑定数据时显示状态信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
              var bllManufacturer = mk.l.Sales_Manufacturer.ToList();
            var bllCategory =mk.l.Sales_MaterialCategory.ToList();
           var bllInventory =mk.l.Sales_MaterialInventory.ToList();

                if (e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)
                {
                    //显示材料类型 厂家信息
                    int intMaterialID = int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["MaterialID"].ToString());
                    Label lblManufacturerName = (Label)(e.Row.FindControl("lblManufacturerName"));
                    Label lblMaterialCategoryName = (Label)(e.Row.FindControl("lblMaterialCategoryName"));
                 Sales_Manufacturer mManufacturer = bllManufacturer.Where(h=>h.ManufacturerID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["ManufacturerID"].ToString())).FirstOrDefault();
                    if (mManufacturer != null)
                    {
                        lblManufacturerName.Text = mManufacturer.ManufacturerName;
                    }
              Sales_MaterialCategory mCategory = bllCategory.Where(h=>h.MaterialCategoryID==int.Parse(this.myGridView.DataKeys[e.Row.RowIndex].Values["MaterialCategoryID"].ToString())).FirstOrDefault();
                    if (mCategory != null)
                    {
                        lblMaterialCategoryName.Text = mCategory.Name;
                    }
                    //显示库存数量
                    Label lblMaterialInventoryQuantity = (Label)(e.Row.FindControl("lblMaterialInventoryQuantity"));
                    lblMaterialInventoryQuantity.Text = bllInventory.Where(y=>y.MaterialID==intMaterialID).Sum(h=>h.Quantity).ToString();
                }
                if (e.Row.RowState == DataControlRowState.Edit || (int)e.Row.RowState == 5)
                {
                    DropDownList ddlMaterialCategoryID = (DropDownList)(e.Row.FindControl("ddlMaterialCategoryID"));
              var ds = bllCategory.ToList();
                    ddlMaterialCategoryID.DataSource = ds;
                    ddlMaterialCategoryID.DataTextField = "Name";
                    ddlMaterialCategoryID.DataValueField = "MaterialCategoryID";
                    ddlMaterialCategoryID.DataBind();
                    ddlMaterialCategoryID.Items.FindByValue(this.myGridView.DataKeys[e.Row.RowIndex].Values["MaterialCategoryID"].ToString()).Selected = true;
                }


                //让数字以文本形式表示
                //e.Row.Cells[0].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                //e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                //e.Row.Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

            }
        }

        /// <summary>
        /// Handles the RowEditing event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.myGridView.EditIndex = e.NewEditIndex;
            this.BindData();
        }

        /// <summary>
        /// Handles the RowCancelingEdit event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewCancelEditEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            this.myGridView.EditIndex = -1;
            this.BindData();
        }

        /// <summary>
        /// Handles the RowUpdating event of the myGridView control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewUpdateEventArgs"/> instance containing the event data.</param>
        protected void myGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            if (this.IsValid)
            {
                this.lblMsg.Text = "";
                TextBox txtName = (TextBox)(this.myGridView.Rows[e.RowIndex].FindControl("txtName"));
                DropDownList ddlMaterialCategoryID = (DropDownList)(this.myGridView.Rows[e.RowIndex].FindControl("ddlMaterialCategoryID"));
                int intMaterialID = int.Parse(this.myGridView.DataKeys[e.RowIndex].Values["MaterialID"].ToString());
             var bll = mk.l.Sales_Material.ToList();
           Sales_Material m = bll.Where(h => h.MaterialID==intMaterialID).FirstOrDefault();
                if (m != null)
                {
                    m.Name = mk.InputText(txtName.Text, 50);
                    m.MaterialCategoryID = int.Parse(ddlMaterialCategoryID.SelectedValue);
                    try
                    {
                       // bll.Update(m);
                        mk.l.SubmitChanges();
                        //提交事务
                     //   ContextUtil.SetComplete();
                    }
                    catch (Exception ex)
                    {
                        //撤销事务
                      //  ContextUtil.SetAbort();
                        this.lblMsg.Text = "修改失败！错误信息：" + ex.Message;
                    }
                }
                this.myGridView.EditIndex = -1;
                this.BindData();
            }
        }

        /// <summary>
        /// Handles the Click event of the btnSearch control.查询相关订单信息
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            this.lblStrWhere.Text = " RootDepartmentID=" + this.lblRootDepartmentID.Text;
            //设置查询条件
            //所有的条件都加and 最后再去掉就行了 tnnd早想到这个办法多好啊 不用写那么多if了
            //设置材料的查询条件
            StringBuilder strWhere = new StringBuilder();
            if (this.txtName.Text.Trim() != "")
            {
                strWhere.AppendFormat(" and Name like '%{0}%'", mk.InputText(this.txtName.Text, 50));
            }
            if (this.ddlMaterialCategoryID.SelectedValue != "0")
            {
                strWhere.Append(" and MaterialCategoryID=" + this.ddlMaterialCategoryID.SelectedValue);
            }
            if (this.ddlManufacturerID.SelectedValue != "0")
            {
                strWhere.Append(" and ManufacturerID=" + this.ddlManufacturerID.SelectedValue);
            }

            if (strWhere.Length > 0)
            {
                //this.lblStrWhere.Text = strWhere.ToString().Substring(5, strWhere.Length - 5);
                this.lblStrWhere.Text += strWhere.ToString();
            }
          //  UART.BLL.Sales.Material bll = new UART.BLL.Sales.Material();
          //  this.AspNetPager.RecordCount = bll.GetCount(this.lblStrWhere.Text);
            this.BindData();
        }

        /// <summary>
        /// Handles the ServerValidate1 event of the CustomValidator1 control.
        /// </summary>
        /// <param name="source">The source of the event.</param>
        /// <param name="args">The <see cref="System.Web.UI.WebControls.ServerValidateEventArgs"/> instance containing the event data.</param>
        protected void CustomValidator1_ServerValidate1(object source, ServerValidateEventArgs args)
        {
var bll = mk.l.Sales_Material.ToList();
            CustomValidator val = (CustomValidator)source;
            //这里要引用父级控件，val的父级是单元格，再父级才是数据行
            GridViewRow gvr = (GridViewRow)(val.Parent.Parent);
           Sales_Material m = bll.Where(h=>h.MaterialID==int.Parse(gvr.Cells[0].Text)).FirstOrDefault();
            TextBox txtName = (TextBox)(val.Parent.FindControl("txtName"));
            DropDownList ddlMaterialCategoryID = (DropDownList)(val.Parent.FindControl("ddlMaterialCategoryID"));
            if (txtName != null)
            {
                string strName = mk.InputText(txtName.Text, 50);
                int intMaterialCategoryID = int.Parse(ddlMaterialCategoryID.SelectedValue);
                int intManufacturerID = int.Parse(this.myGridView.DataKeys[gvr.RowIndex].Values["ManufacturerID"].ToString());
                //要先判断一下，如果更改了产品名称的话，判断是否存在重复数据
                if (m.Name != strName)
                {
                    if (bll.Exists(y=>y.MaterialCategoryID==intMaterialCategoryID& y.ManufacturerID==intManufacturerID&y.Name==strName))
                    {
                        args.IsValid = false;
                    }
                    else
                    {
                        args.IsValid = true;
                    }
                }
                else
                {
                    args.IsValid = true;
                }
            }
            else
            {
                args.IsValid = false;
            }
        }


    }
}
